package com.gsx.handler;


import com.gsx.entity.UserInfo;
import com.gsx.mapper.UserMapper;
import com.gsx.utils.SpringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;


public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    private static UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper){
        MyAuthenticationSuccessHandler.userMapper=userMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {
        if(userMapper==null){
            /*同过配置类来实现注入的方法*/
            userMapper= SpringUtils.getBean(UserMapper.class);
        }
        User user =(User) authentication.getPrincipal();
        Collection<GrantedAuthority> authorities= user.getAuthorities();
        httpServletRequest.getSession().setAttribute("user",userMapper.getUserInfo(user.getUsername()));
        /*toString的结果是权限加上[]括号*/
        if (authorities.toString().equals("[admain]")){
                httpServletResponse.sendRedirect("/admain/index");
        }else {
                httpServletResponse.sendRedirect("/");
        }
    }
}
